package com.example.stray_animal_management_system.admin.Statistics;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/8
 */
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import oshi.SystemInfo;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OperatingSystem;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.*;

@RestController
public class ServerInfoController {

    @GetMapping("/api/admin/server/resource")
    public Map<String, Object> getServerResourceInfo() {
        Map<String, Object> res = new HashMap<>();

        // CPU 信息
        res.put("cpuUsage", getCpuUsage());
        res.put("cpuCores", getCpuCores());
        res.put("cpuModel", getCpuModel());

        // 内存信息
        res.put("memoryUsage", getMemoryUsage());
        res.put("memoryUsed", getMemoryUsed());
        res.put("memoryTotal", getMemoryTotal());

        // 磁盘信息
        res.put("diskUsage", getDiskUsage());
        res.put("diskUsed", getDiskUsed());
        res.put("diskTotal", getDiskTotal());

        // 操作系统信息
        res.put("osName", getOsName());
        res.put("osVersion", getOsVersion());
        res.put("uptime", getUptime());
        res.put("hostname", getHostName());
        res.put("ipAddress", getIpAddress());
        res.put("javaVersion", getJavaVersion());

        // JVM 内存信息
        res.put("jvmTotalMemory", getJvmTotalMemory());
        res.put("jvmUsedMemory", getJvmUsedMemory());
        res.put("jvmMaxMemory", getJvmMaxMemory());

        // 网络信息
        res.put("networkInfo", getNetworkInfo());

        return res;
    }

    // CPU 使用率
    private double getCpuUsage() {
        OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        return osBean.getSystemLoadAverage();  // 获取系统负载
    }

    // CPU 核心数
    private int getCpuCores() {
        OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        return osBean.getAvailableProcessors(); // 获取可用的 CPU 核心数
    }

    // CPU 型号
    private String getCpuModel() {
        return "CPU model info not available in Java";  // 可以通过特定的库获取 CPU 型号，例如 `oshi`
    }

    // 内存使用情况
    private String getMemoryUsage() {
        return String.format("%.2f%%", (double) getMemoryUsed() / getMemoryTotal() * 100);
    }

    private long getMemoryUsed() {
        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    }

    private long getMemoryTotal() {
        return Runtime.getRuntime().maxMemory();
    }



    // 磁盘信息
    private String getDiskUsage() {
        File[] roots = File.listRoots();
        StringBuilder diskInfo = new StringBuilder();
        for (File root : roots) {
            diskInfo.append("Drive: ").append(root.getPath())
                    .append(", Total: ").append(root.getTotalSpace() / (1024 * 1024 * 1024)).append(" GB")
                    .append(", Free: ").append(root.getFreeSpace() / (1024 * 1024 * 1024)).append(" GB")
                    .append("\n");
        }
        return diskInfo.toString();
    }

    private long getDiskUsed() {
        File[] roots = File.listRoots();
        long totalUsed = 0;
        for (File root : roots) {
            totalUsed += (root.getTotalSpace() - root.getFreeSpace());
        }
        return totalUsed;
    }

    private long getDiskTotal() {
        File[] roots = File.listRoots();
        long totalSpace = 0;
        for (File root : roots) {
            totalSpace += root.getTotalSpace();
        }
        return totalSpace;
    }

    // 操作系统信息
    private String getOsName() {
        return System.getProperty("os.name");
    }

    private String getOsVersion() {
        return System.getProperty("os.version");
    }
    /**
     * 获取系统的 uptime（运行时间）
     *
     * @return 系统的运行时间（单位：毫秒）
     */
    public static long getUptime() {
        long uptime = 0;

        // 获取操作系统的管理信息
        String os = System.getProperty("os.name").toLowerCase();

        if (os.contains("win")) {
            uptime = getUptimeForWindows();
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            uptime = getUptimeForUnix();
        }

        return uptime;
    }

    /**
     * 获取 Linux 或 macOS 系统的 Uptime
     *
     * @return 系统运行时间（单位：毫秒）
     */
    private static long getUptimeForUnix() {
        try {
            Process process = Runtime.getRuntime().exec("cat /proc/uptime");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = reader.readLine();
            String[] parts = line.split(" ");
            double uptimeInSeconds = Double.parseDouble(parts[0]);
            return (long) (uptimeInSeconds * 1000); // 转换为毫秒
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取 Windows 系统的 Uptime
     *
     * @return 系统运行时间（单位：毫秒）
     */
    private static long getUptimeForWindows() {
        try {
            String cmd = "systeminfo | find \"System Boot Time\"";
            Process process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
            // 处理命令输出，提取系统启动时间并计算 uptime
            // 可根据实际需求改进命令解析
            return 0L;  // 返回假设的结果（需要根据实际输出进一步实现）
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void main(String[] args) {
        System.out.println("System Uptime: " + getUptime() + " ms");
    }


    private String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            return "Unknown";
        }
    }

    private String getIpAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            return "Unknown";
        }
    }

    private String getJavaVersion() {
        return System.getProperty("java.version");
    }

    // JVM 内存信息
    private long getJvmTotalMemory() {
        return Runtime.getRuntime().maxMemory();
    }

    private long getJvmUsedMemory() {
        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    }

    private long getJvmMaxMemory() {
        return Runtime.getRuntime().maxMemory();
    }

    // 网络信息
    private List<Map<String, String>> getNetworkInfo() {
        List<Map<String, String>> networkInfoList = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    Map<String, String> networkInfo = new HashMap<>();
                    networkInfo.put("name", networkInterface.getName());
                    networkInfo.put("ip", inetAddress.getHostAddress());
                    networkInfo.put("status", networkInterface.isUp() ? "Up" : "Down");
                    networkInfoList.add(networkInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return networkInfoList;
    }
}